<?php

namespace App\Http\Controllers;

use App\Http\Helpers\PasswordHelper;
use App\Http\Helpers\StatusResponse;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class UserController extends Controller
{
    /**
     * 添加管理员用户
     */
    public function addAdminUser () : JsonResponse
    {
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        $user = User::query()->create([
            'name' => \request('name'),
            'password' => \request('password'),
            'email' => \request('email'),
            'level' => \request('level')
        ]);
        if ($user) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 修改用户等级
     * @return JsonResponse
     */
    public function changeLevel ($id) : JsonResponse
    {
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (!$user = User::query()->find($id)) {
            return $this->failWithArr(StatusResponse::USER_NOT_FOUND);
        }
        if ($user->update([
            'level' => \request('level')
        ])) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 获取全部用户
     * @return JsonResponse
     */
    public function getAll () : JsonResponse
    {
        if (!$this->isAdmin()) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (!$users = User::query()->paginate(10)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        return $this->success($users);
    }

    /**
     * 获取用户的信息
     * @param $id
     * @return JsonResponse
     */
    public function getUser ($id) : JsonResponse
    {
        if (!$this->isAdminOrSelf($id))
        {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (!$user = User::query()->find($id)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        return $this->success($user);
    }

    /**
     * 禁用目标用户
     * @param $id
     * @return JsonResponse
     */
    public function disable ($id) : JsonResponse
    {
        return $this->failWithArr(StatusResponse::NOT_OPENED);
    }

    /**
     * 删除用户
     * @param $id
     * @return JsonResponse
     */
    public function remove ($id) : JsonResponse
    {
        if (!$this->isAdminOrSelf($id)) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if ($this->getUserId() === (int)$id) {
            return $this->failWithArr(StatusResponse::CAN_NOT_REMOVE_SELF);
        }
        if (User::query()->find($id)->delete()) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 编辑用户信息
     * @param $id
     * @return JsonResponse
     */
    public function editUser ($id) : JsonResponse
    {
        if (!$this->isAdminOrSelf($id)) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (User::query()->find($id)->update([
            'name' => request('username')
        ])) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    /**
     * 修改用户密码
     * @param $id
     * @return JsonResponse
     */
    public function changePassword ($id) : JsonResponse
    {
        if (!$this->isSelf($id)) {
            return $this->failWithArr(StatusResponse::PERMISSION_REQUIRE);
        }
        if (!$user = User::query()->find($id)) {
            return $this->failWithArr(StatusResponse::NOT_FOUND);
        }
        if ($user->password != request('old_password')) {
            return $this->failWithArr(StatusResponse::USER_PASSWORD_ERROR);
        }
        if ($user->update([
            'password' => request('password')
        ])) {
            return $this->success();
        }
        return $this->unknown_err();
    }

    public function checkPassword() : JsonResponse
    {
        if (User::query()->find($this->getUserId())->password != \request('password')) {
            return $this->failWithArr(StatusResponse::USER_PASSWORD_ERROR);
        }
        return $this->success();
    }

    /**
     * 无密码注册
     * @return JsonResponse
     */
    public function noPwdRegister () :JsonResponse
    {
        // 用户邮箱
        $email = \request('email');
        // 用户名
        $username = \request('username');
        // 检查用户是否存在
        if (User::query()->where('email', $email)->first()) {
            return $this->failWithArr(StatusResponse::USER_EXIST);
        }
        // 生成默认密码
        $password = PasswordHelper::generate_password(12);
        // 保存用户信息
        if (!$user = User::query()->create([
            'name' => $username,
            'email' => $email,
            'password' => $password
        ])) {
            return $this->unknown_err();
        }
        Mail::send('mail', ['name' => $username, 'password' => $password], function ($message) {
            $message->from('wafer_blog@mczhengyi.top', 'wafer_blog');
            $message->to(\request('email'));
            $message->subject('账户密码生成提醒');
        });
        // 自动登录
        $token = Auth::guard('api')->login($user);
        if ($token) {
            $user->remember_token = $token;
            $user->save();
            return $this->success([
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => Auth::guard('api')->factory()->getTTL() * 60
            ]);
        }
        return $this->unknown_err();
    }

    public function checkUserExist ($email) {
        if (User::query()->where('email', $email)->first()) {
            return $this->success(['exist' => true]);
        }
        return $this->success(['exist' => false]);
    }
}
